<template>
  <div id="app">
    <!-- Header -->
    <header class="header can-sticky">
      <el-row type="flex" justify="space-between" align="middle" class="container">
        <el-col :span="4">
          <div class="logo">
            <a href="/home">
              <img src="@/assets/images/logo.png" alt="logo" />
            </a>
          </div>
        </el-col>
        <el-col :span="16">
          <nav class="navigation">
            <ul class="main-menu">
              <li
                v-for="(item, index) in mainMenu"
                :key="index"
                class="menu-item"
                :class="{ 'menu-item-has-children': !!item.children }"
              >
                <a :href="item.href" @click="handleMenuClick(item, $event)">
                  {{ item.title }}
                </a>

                <!-- 二级菜单 -->
                <ul v-if="item.children" class="sub-menu">
                  <li
                    v-for="(child, childIdx) in item.children"
                    :key="childIdx"
                    class="menu-item"
                    :class="{ 'menu-item-has-children': !!child.children }"
                  >
                    <a :href="child.href" @click="handleMenuClick(child, $event)">
                      {{ child.title }}
                    </a>

                    <!-- 三级菜单 -->
                    <ul v-if="child.children" class="sub-menu">
                      <li
                        v-for="(grandChild, gIdx) in child.children"
                        :key="gIdx"
                        class="menu-item"
                      >
                        <a :href="grandChild.href">{{ grandChild.title }}</a>
                      </li>
                    </ul>
                  </li>
                </ul>
              </li>
            </ul>
          </nav>
        </el-col>
<!--        <el-col :span="4" class="text-right">-->
<!--          <a href="/login" class="header_btn thm-btn btn-rounded btn-small">Log In</a>-->
<!--        </el-col>-->
      </el-row>
    </header>

    <!-- Subheader  -->
    <div class="section-bg section-padding subheader">
      <el-container>
        <el-main>
          <div class="container">
            <el-row type="flex" justify="center">
              <el-col :span="24" class="text-center">
                <h1 class="text-white page-title">Blog Grid</h1>
              </el-col>
            </el-row>
          </div>
        </el-main>
      </el-container>
    </div>

    <!-- Blog List Section -->
    <section class="section-padding section">
      <div class="container">
        <!-- 博客列表 -->
        <div class="row justify-content-center">
          <!-- 单个博客项 -->
          <article
            v-for="blog in projectBlogs"
            :key="blog.id"
            class="col-lg-4 col-md-6"
          >
            <!-- 博客卡片 -->
            <div
              class="blog-card"
              @click="goToBlogDetails(blog.id)"
              style="cursor: pointer;"
            >
              <!-- 封面图 -->
              <div class="post_image responsive-image" >
                <img
                  :src="fixImgUrl(blog.coverImage)"
                  alt="博客封面"
                  class="object-cover"
                />
              </div>

              <!-- 内容区 -->
              <div class="post_caption p-3">
                <div class="post_date text-muted small">
                  {{ blog.createdAt }}
                </div>
                <h2 class="post_title h5 mb-1">
                  {{ blog.title }}
                </h2>
                <p class="text-secondary small mb-0">
                  {{ blog.subtitle }}
                </p>
              </div>
            </div>
          </article>
        </div>

        <!-- 分页（静态结构，后续可绑定事件） -->
<!--        <div class="row mt-4">-->
<!--          <div class="col-12">-->
<!--            <nav>-->
<!--              <ul class="pagination justify-content-center">-->
<!--                <li class="page-item" :class="{ disabled: currentPage === 1 }">-->
<!--                  <a class="page-link" href="#" @click.prevent="prevPage">«</a>-->
<!--                </li>-->
<!--                <li-->
<!--                  v-for="page in totalPages"-->
<!--                  :key="page"-->
<!--                  class="page-item"-->
<!--                  :class="{ active: currentPage === page }"-->
<!--                >-->
<!--                  <a class="page-link" href="#" @click.prevent="goToPage(page)">{{ page }}</a>-->
<!--                </li>-->
<!--                <li class="page-item" :class="{ disabled: currentPage === totalPages }">-->
<!--                  <a class="page-link" href="#" @click.prevent="nextPage">»</a>-->
<!--                </li>-->
<!--              </ul>-->
<!--            </nav>-->
<!--          </div>-->
<!--        </div>-->
      </div>
    </section>


  </div>
</template>

<script>
import {listCases, updateCases} from "@/api/achievement/cases"
export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 6, // 每页显示6条
      blogList: [],
      loading: false,
      error: null,
      mainMenu: [
        {
          title: '首页',
          href: '/home'
        },
        {
          title: '关于',
          href: '/about'
        },
        {
          title: '服务',
          href: '/services',
        },
        {
          title: '博客',
          href: '#',
          children: [
            {
              title: '博客网络',
              href: '#',
              children: [
                { title: '全宽', href: '/blog-grid' },
                { title: '左侧边栏', href: '/blog-grid-left' },
                { title: '右侧边栏', href: '/blog-grid-right' }
              ]
            },
          ]
        },
        {
          title: '联系我们',
          href: '/contact'
        }
      ]
    };
  },
  computed: {
    // 总页数
    totalPages() {
      return Math.ceil(this.blogList.length / this.pageSize);
    },
    // 当前页显示的数据
    // displayedBlogs() {
    //   const start = (this.currentPage - 1) * this.pageSize;
    //   return this.blogList.slice(start, start + this.pageSize);
    // },
    projectBlogs() {
      // 过滤出 type 为 "project" 的博客,再按创建时间倒序排列
      return this.blogList
        .filter(blog => blog.type === 'project')
        .slice() // 创建副本，避免修改原数组
        .sort((a, b) => {
          const dateA = new Date(a.createdAt);
          const dateB = new Date(b.createdAt);
          return dateB - dateA; // 倒序：最新在前
        });
    }
  },
  created() {
    this.fetchBlogList(); // 获取博客列表
  },
  methods: {
    fixImgUrl(path) {
      if (!path) return '';
      return path.startsWith(process.env.VUE_APP_BASE_API) ? encodeURI(path) : encodeURI(process.env.VUE_APP_BASE_API + path);
    },
    fetchBlogList() {
      this.loading = true; // 开启加载状态
      const queryParams = {
        pageNum: 1,
        pageSize: 6,
        type: 'project',
        isPublished: 1
      };
      listCases(queryParams)
        .then(response => {
          console.log('API 返回数据:', response);

          // 把 API 返回的数据赋值给模板中使用的变量
          this.blogList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch(error => {
          console.error('获取博客列表失败:', error);
          this.loading = false;
        });
      },

    // 跳转详情页
    goToBlogDetails(id) {
      const blog = this.blogList.find(c => c.id === id);
      if (blog) {
        const data = {
          id: blog.id,
          viewCount: (blog.viewCount || 0)  + 1
        };
        updateCases(data).then(() => {
          console.log(`博客 ${id} 阅读量已 +1`);
        }).catch(err => {
          console.error('更新失败:', err);
        }).finally(() => {
          // 无论成功失败都跳转
          this.$router.push({ path: `/blog-details/${id}` });
        });
      } else {
        this.$router.push({ path: `/blog-details/${id}` });
      }
    },
    // 分页方法
    goToPage(page) {
      if (page < 1 || page > this.totalPages) return;
      this.currentPage = page;
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      }
    },

    handleMenuClick(item, event) {
      // 如果有子菜单，阻止跳转，用于展开/收起
      if (item.children) {
        event.preventDefault();
        // 可以在这里添加展开/收起逻辑（比如维护一个展开状态数组）
        console.log('Toggle submenu for:', item.title);
      }
      // 否则允许正常跳转
    }
  }
}
</script>

<style scoped>
/* 全局重置与字体 */
#app {
  font-family: 'Poppins', sans-serif;
  margin: 0;
  padding: 0;
}

/* 容器居中，类似 Bootstrap */
.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
}

/* =============
   Header 样式
============= */
.header {
  background-color: #ffffff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 15px 0;
  position: relative;
  z-index: 1000;
}

.header.can-sticky {
  position: sticky;
  top: 0;
  transition: all 0.3s ease;
}

.logo img {
  height: 50px;
  transition: all 0.3s ease;
}

.logo img:hover {
  opacity: 0.9;
}

/* 导航栏 - 主菜单 */
.navigation {
  display: flex;
  justify-content: center;
}

.main-menu {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  gap: 30px;
  align-items: center;
}

.main-menu > .menu-item {
  position: relative;
}

.main-menu > .menu-item > a {
  text-decoration: none;
  color: #333;
  font-weight: 500;
  font-size: 16px;
  transition: color 0.3s ease;
  padding: 5px 0;
  display: block;
}

.main-menu > .menu-item > a:hover,
.main-menu > .menu-item > a.active {
  color: #0066ff;
}

/* 二级菜单 */
.sub-menu {
  position: absolute;
  top: 100%;
  left: 0;
  background: #fff;
  min-width: 200px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  opacity: 0;
  visibility: hidden;
  transform: translateY(-10px);
  transition: all 0.3s ease;
  list-style: none;
  margin: 0;
  padding: 10px 0;
  z-index: 1001;
}

.menu-item-has-children:hover > .sub-menu {
  opacity: 1;
  visibility: visible;
  transform: translateY(0);
}

.sub-menu .menu-item {
  padding: 0;
}

.sub-menu .menu-item > a {
  color: #555;
  padding: 10px 20px;
  font-size: 15px;
  display: block;
  transition: background 0.3s ease, color 0.3s ease;
}

.sub-menu .menu-item > a:hover {
  background-color: #f5f9ff;
  color: #0066ff;
  padding-left: 24px;
}

/* 三级菜单 */
.sub-menu .sub-menu {
  left: 100%;
  top: 5px;
}

/* 登录按钮 */
.header_btn {
  background-color: #0066ff;
  color: #fff !important;
  padding: 10px 20px;
  text-decoration: none;
  border-radius: 30px;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: inline-block;
  border: none;
  outline: none;
}

.header_btn:hover {
  background-color: #0052cc;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 102, 255, 0.3);
}

/* =============
   Subheader 样式
============= */
.subheader {
  background-image: url('https://images.unsplash.com/photo-1499750310107-5fef28a66643?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  padding: 100px 0;
  color: #fff;
  position: relative;
}

.subheader::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6); /* 深色遮罩提升文字可读性 */
  z-index: 1;
}

.subheader .el-main {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-title {
  font-size: 3rem;
  font-weight: 700;
  margin: 0;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  letter-spacing: -0.5px;
}

.text-white {
  color: #ffffff;
}

.text-center {
  text-align: center;
}

/* =============
   响应式设计
============= */
@media (max-width: 992px) {
  .main-menu {
    gap: 20px;
  }

  .page-title {
    font-size: 2.5rem;
  }
}

@media (max-width: 768px) {
  .header {
    padding: 12px 0;
  }

  .logo img {
    height: 40px;
  }

  .main-menu {
    gap: 15px;
    flex-wrap: wrap;
    justify-content: center;
  }

  .main-menu > .menu-item {
    font-size: 14px;
  }

  .sub-menu {
    min-width: 180px;
  }

  .sub-menu .menu-item > a {
    padding: 8px 16px;
    font-size: 14px;
  }

  .page-title {
    font-size: 2rem;
  }

  .container {
    padding: 0 15px;
  }
}

@media (max-width: 576px) {
  .main-menu {
    gap: 10px;
    font-size: 14px;
  }

  .header_btn {
    padding: 8px 16px;
    font-size: 13px;
  }

  .page-title {
    font-size: 1.8rem;
  }
}

/* 博客卡片悬停效果 */
.blog-card {
  border-radius: 8px;
  transition: all 0.3s ease;
  padding: 10px;
}

.blog-card:hover {
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
  background-color: #f9f9f9;
}

/* 博客卡片样式 */
.blog-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.blog-card:hover {
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
  transform: translateY(-4px);
  border-color: #007bff;
}

/* 图片容器 */
.post_image {
  height: 200px;
  overflow: hidden;
}

.post_image img {
  transition: transform 0.4s ease;
}

.blog-card:hover .post_image img {
  transform: scale(1.05);
}

/* 日期样式 */
.post_date {
  font-size: 0.8rem;
  color: #6c757d;
}

/* 标题和副标题 */
.post_title {
  color: #2c3e50;
  font-weight: 600;
  transition: color 0.3s;
}

.blog-card:hover .post_title {
  color: #007bff;
}

/* 副标题 */
.text-secondary {
  color: #6c757d !important;
}

.responsive-image {
  position: relative;
  width: 100%;
  height: 0;
  padding-top: 56.25%; /* 16:9 比例 (9 ÷ 16 = 0.5625) */
  overflow: hidden;
}

.responsive-image img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: center;
}
</style>

